package logic

import (
	"context"

	"github.com/Terry-Mao/goim/internal/logic/model"

	log "github.com/golang/glog"
)

// 对一批 channel 的 key 推送
func (l *Logic) PushKeys(c context.Context, op int32, keys []string, msg []byte) (err error) {
	// 按顺序返回 key 对应的 server
	servers, err := l.dao.ServersByKeys(c, keys)
	if err != nil {
		return
	}
	// 把同一个 server 上的 key 放到一起
	pushKeys := make(map[string][]string)
	for i, key := range keys {
		server := servers[i]
		if server != "" && key != "" {
			pushKeys[server] = append(pushKeys[server], key)
		}
	}
	// 对每个 server 执行一次推送，方便 job 上的消费者转发推送到 comet
	for server, keys := range pushKeys {
		if err = l.dao.PushMsg(c, op, server, keys, msg); err != nil {
			return
		}
	}
	return
}

// 对一批用户推送
func (l *Logic) PushMids(c context.Context, op int32, mids []int64, msg []byte) (err error) {
	// 找到 mids 对应的所有 key -> server
	keyServers, _, err := l.dao.KeysByMids(c, mids)
	if err != nil {
		return
	}
	// 把同一个 server 上的 key 放到一起
	pushKeys := make(map[string][]string)
	for key, server := range keyServers {
		if key == "" || server == "" {
			log.Warningf("push key:%s server:%s is empty", key, server)
			continue
		}
		pushKeys[server] = append(pushKeys[server], key)
	}
	// 对每个 server 执行一次推送，方便 job 上的消费者转发推送到 comet
	for server, keys := range pushKeys {
		if err = l.dao.PushMsg(c, op, server, keys, msg); err != nil {
			return
		}
	}
	return
}

// 对房间广播，
// 把 typ 和 room 拼接成的 roomid 格式："live://1000a"
func (l *Logic) PushRoom(c context.Context, op int32, typ, room string, msg []byte) (err error) {
	return l.dao.BroadcastRoomMsg(c, op, model.EncodeRoomKey(typ, room), msg)
}

// 全局广播
func (l *Logic) PushAll(c context.Context, op, speed int32, msg []byte) (err error) {
	return l.dao.BroadcastMsg(c, op, speed, msg)
}
